<?php


namespace api\app\controller;

use api\app\model\OrderModel;
use api\app\model\UserModel;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class MoneyController extends RestBaseController
{
    //充值余额
    public function add(Request $request)
    {
        $id = $request->token;
        //接收
        $money = input('post.money','');
        //判断
        if (empty($money)) {
            $this->error('参数错误');
        }
        $user = UserModel::find($id);
        if (!$user) {
            $this->error('错误');
        }
        //支付验证
        //支付验证


        // 启动事务
        Db::startTrans();

        try {
            //记录
            $addLog = addMoneyLog($id,$money,'充值余额',$user['money'],1);
            //充值
            $inc = UserModel::where('id',$id)->inc('money',$money)->update();

        } catch (\Exception $exception) {
            // 回滚事务
            Db::rollback();
            $this->error('充值失败');
        }

        if ($inc && $addLog) {
            // 提交事务
            Db::commit();
            $this->success('充值成功');
        }else{
            // 回滚事务
            Db::rollback();
            $this->error('充值失败');
        };

    }

    //余额支付
    public function pay(Request $request)
    {
        $orderId = input('post.order_id');
        //查询订单列表
        $order = OrderModel::find($orderId);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order['switch'] != 0) {
            $this->error('订单已支付');
        }
        //查询用户列表
        $user = UserModel::find($request->token);
        if (!$user) {
            $this->error('错误');
        }
        if ($user['money'] < $order['price']) {
            $this->error('余额不足');
        }
        Db::startTrans();
        //订单状态修改
        $orderSwitch = false;
        //流水记录
        $moneyLog = false;
        //扣掉用户余额
        $userMoney = false;
        try {
            $order->switch = 1;
            $order->pay_type = 1;
            $orderSwitch = $order->save();
            $moneyLog = addMoneyLog($request->token,$order['price'],'支付',$user['money'],0);
            $userMoney = UserModel::where('id',$order['user_id'])->dec('money',$order['total_price'])->update();
        }catch (\Exception $exception) {
            Db::rollback();
            $this->error('支付失败');
        }
        if ($orderSwitch && $moneyLog && $userMoney) {
            Db::commit();
            $this->success('支付成功');
        }else{
            Db::rollback();
            $this->error('支付失败');
        };

    }

}